package com.qili.aspect;

import com.qili.annotation.MenuPermision;
import com.qili.core.utils.DictTypes;
import com.qili.entity.base.BaseDict;
import com.qili.service.base.BaseDictService;
import com.qili.util.AuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
/**
 * @Auther liuyang
 * @Date
 * @Version
 */
@Slf4j
@Aspect
@Component
@SuppressWarnings({"unused"})
public class MenuPermisionAspect {

    @Autowired
    private BaseDictService baseDictService;

    @Pointcut("@annotation(com.qili.annotation.MenuPermision)")
    public void annotationPointcut() {
    }

    /**
     * 判断用户的权限(菜单)列表中的菜单权限,是否包含当前需要的权限(注解传过来的参数)
     * 如果有权限,    nothing
     * 如果没有权限   到字典中查询该权限的自定义无权限提示,设置到request中,转发到没有菜单权限页面
     * @param joinPoint
     * @throws ServletException
     * @throws IOException
     */
    @Before("annotationPointcut()")
    public void beforePointcut(JoinPoint joinPoint) throws ServletException, IOException {
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();
        Method method = ms.getMethod();
        MenuPermision annotation = method.getAnnotation(MenuPermision.class);
        String per = annotation.value();
        boolean b = AuthUtil.checkHaveMenuAuth(per);
        if(!b){
            BaseDict baseDict = new BaseDict();
            baseDict.setBadtCode(per);
            baseDict.setBadtTypecode(DictTypes.QSQXTS.getType());
            BaseDict baseDict1 = baseDictService.selectOne(baseDict);
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            HttpServletResponse response = attributes.getResponse();
            if(null != baseDict1 && StringUtils.isNotBlank(baseDict1.getBadtName())){
                request.setAttribute("msg",baseDict1.getBadtName());
            }
            request.getRequestDispatcher("/error/noMenuPer").forward(request, attributes.getResponse());
        }
    }

}
